import React, { useEffect, useState } from 'react';
import { Editor } from '@bytemd/react';
import gfm from '@bytemd/plugin-gfm';
import highlight from '@bytemd/plugin-highlight';
import mediumZoom from '@bytemd/plugin-medium-zoom';
import math from '@bytemd/plugin-math';
import { connect } from 'react-redux';
import {
  Button,
  makeStyles,
  Dialog,
  DialogTitle,
  DialogContent,
  FormControl,
  FormLabel,
  RadioGroup,
  FormControlLabel,
  Radio,
  DialogActions,
  IconButton,
  Snackbar,
} from '@material-ui/core';
import { Alert } from '@material-ui/lab';
import ImageIcon from '@material-ui/icons/Image';
import { useParams, useHistory } from 'react-router-dom';
import { debounce } from 'lodash';
import { fileUpload } from '../../api/actions/base';
import {
  getArticleById,
  updateArticleById,
  publish,
} from '../../api/actions/article';

import 'bytemd/dist/index.min.css';
import 'github-markdown-css/github-markdown.css';
import 'highlight.js/styles/github.css';
import './index.css';

const plugins = [gfm(), highlight(), mediumZoom(), math()];

const useStyles = makeStyles((theme) => ({
  header: {
    width: '100%',
    height: '60px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  input: {
    margin: 0,
    paddingLeft: 10,
    fontSize: '1.5rem',
    fontWeight: 700,
    color: '#000',
    border: 'none',
    outline: 'none',
    backgroundColor: 'none',
    flex: 1,
  },
  tools: {
    display: 'flex',
    alignItems: 'center',
    flex: 0.25,
    color: '#777',
  },
  markdown: {
    backgroundColor: 'rgba(0,0,0,0.03) !important',
  },
  draft: {
    margin: theme.spacing(0, 1, 0, 0),
  },
  uploadInput: {
    display: 'none',
  },
}));

function App() {
  // const { user } = props;

  const params = useParams();
  const history = useHistory();
  const classes = useStyles();

  const [title, setTitle] = useState('');
  const [value, setValue] = useState('');
  const [publishDialogOpen, setPublishDialogOpen] = useState(false);
  const [alertOpen, setAlertOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [errorMessage, setErrorMessage] = useState();
  const [articleType, setArticleType] = useState();
  const [successOpen, setSuccessOpen] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');

  const [autoSaveFunc] = useState(() => debounce(async (title, value) => {
    setSaving(true);
    const { id } = params;
    await updateArticleById({
      id,
      title,
      post: value,
    });
    setSaving(false);
  }, 700));

  const handleAlertClose = () => setAlertOpen(false);
  const handleSuccessClose = () => setSuccessOpen(false);
  const handleWillPublish = () => {
    if (title) {
      setPublishDialogOpen(true);
    } else {
      setErrorMessage('请输入文章标题');
      setAlertOpen(true);
    }
  };

  const handlePublish = async () => {
    const { id } = params;
    const res = await publish({
      id,
      type: articleType,
    });
    if (res.code === 0) {
      setSuccessOpen(true);
      setSuccessMessage('发布成功');
      setPublishDialogOpen(false);
    }
  };

  const handleClose = () => {
    setPublishDialogOpen(false);
  };

  const handlePostChange = (value) => {
    setValue(value);
  };

  const handleImageUpload = async (files) => {
    const res = [];
    for (let i = 0; i < files.length; i += 1) {
      const formData = new FormData();
      formData.append('file', files[i]);
      // eslint-disable-next-line no-await-in-loop
      const result = await fileUpload(formData);
      res.push({
        url: result.data.url,
        alt: result.data.name,
        title: result.data.name,
      });
    }
    return res;
  };

  const handleTypeChange = (e) => {
    setArticleType(e.target.value);
  };

  const onUpload = async (e) => {
    const file = e.target.files[0];
    const formData = new FormData();
    formData.append('file', file);

    const result = await fileUpload(formData);
    console.log(result);
  };

  // 自动保存
  useEffect(() => {
    setSaving(true);
    autoSaveFunc(title, value);
  }, [title, value]);

  // 初始化编辑器
  useEffect(() => {
    const fetchData = async (id) => {
      const res = await getArticleById({ id });
      if (res.code === 0) {
        const { data } = res;
        setTitle(data.title);
        setValue(data.post);
      }
    };
    const { id } = params;
    if (id) {
      fetchData(id);
    } else {
      history.push('/404');
    }
  }, [params]);

  return (
    <div>
      <Snackbar
        open={alertOpen}
        autoHideDuration={3000}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert onClose={handleAlertClose} severity="error">
          {errorMessage}
        </Alert>
      </Snackbar>
      <Snackbar
        open={successOpen}
        autoHideDuration={3000}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert onClose={handleSuccessClose} severity="success">
          {successMessage}
        </Alert>
      </Snackbar>
      <header className={classes.header}>
        <input
          className={classes.input}
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder="请输入文章标题..."
        />
        <div className={classes.tools}>
          {saving ? '保存中...' : '文章将自动保存至'}
          <Button size="large" className={classes.draft}>
            草稿
          </Button>
          <input
            accept="image/*"
            className={classes.uploadInput}
            id="icon-button-file"
            type="file"
            onChange={onUpload}
          />
          {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
          <label htmlFor="icon-button-file">
            <IconButton color="primary" component="span">
              <ImageIcon />
            </IconButton>
          </label>
          <Button size="large" color="primary" onClick={handleWillPublish}>
            发布
          </Button>
        </div>
        <Dialog
          open={publishDialogOpen}
          onClose={handleClose}
          aria-labelledby="form-dialog-title"
        >
          <DialogTitle id="form-dialog-title">发布前的设置</DialogTitle>
          <DialogContent>
            <FormControl component="fieldset">
              <FormLabel component="legend">分类</FormLabel>
              <RadioGroup
                row
                aria-label="position"
                name="position"
                defaultValue="top"
                onChange={handleTypeChange}
              >
                <FormControlLabel
                  value="frontend"
                  control={<Radio color="primary" />}
                  label="前端"
                />
                <FormControlLabel
                  value="backend"
                  control={<Radio color="primary" />}
                  label="后端"
                />
                <FormControlLabel
                  value="android"
                  control={<Radio color="primary" />}
                  label="Android"
                />
                <FormControlLabel
                  value="ios"
                  control={<Radio color="primary" />}
                  label="iOS"
                />
                <FormControlLabel
                  value="ai"
                  control={<Radio color="primary" />}
                  label="人工智能"
                />
                <FormControlLabel
                  value="freebie"
                  control={<Radio color="primary" />}
                  label="开发工具"
                />
                <FormControlLabel
                  value="career"
                  control={<Radio color="primary" />}
                  label="代码人生"
                />
                <FormControlLabel
                  value="article"
                  control={<Radio color="primary" />}
                  label="阅读"
                />
              </RadioGroup>
            </FormControl>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleClose} color="primary">
              取消
            </Button>
            <Button
              onClick={handlePublish}
              color="primary"
              disabled={!articleType}
            >
              发布
            </Button>
          </DialogActions>
        </Dialog>
      </header>
      <Editor
        uploadImages={handleImageUpload}
        value={value}
        plugins={plugins}
        onChange={handlePostChange}
      />
    </div>
  );
}
const mapStateToProps = (state) => ({
  user: state.user,
});

export default connect(mapStateToProps, null)(App);
